package com.jzxk.stu.algorithm;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 今朝惜客
 * @CreateTime : 16/9/19 上午11:28
 * @Description : 冒泡排序
 */
public class BubbleSort {

	/**
	 *
	 * 冒泡排序:
	 * 基本思想:在要排序的一组数中，对当前还未排好序的范围内的全部数，自上而下对相邻的两个数依次进行比较和调整，
	 * 让较大的数往下沉，较小的往上冒。即：每当两相邻的数比较后发现它们的排序与排序要求相反时，就将它们互换。
	 */

	private static final Logger LOG= LoggerFactory.getLogger(BubbleSort.class);

	/**
	 * 按从小到大排序(从前往后)
	 *
	 * @param numbers 待排序数组
	 */
	public static void sortByAscFromFront(Integer[] numbers) {

		boolean transFlag = true;//是否发生交换

		int i=1;

		while (transFlag) {
			transFlag=false;
			for (int j = 0; j < numbers.length - 1; j++) {

				if (numbers[j] > numbers[j + 1]) {

					int temp = numbers[j];
					numbers[j] = numbers[j + 1];
					numbers[j + 1] = temp;
					transFlag=true;
				}

				//LOG.info("{}:{}","第"+i+"趟,第"+(j+1)+"轮",Arrays.toString(numbers));
			}

			//LOG.info("第{}趟:{}",i++,Arrays.toString(numbers));
		}
	}

	/**
	 * 按从大到小排序(从前往后)
	 *
	 * @param numbers 待排序数组
	 */
	public static void sortByDescFromFront(Integer[] numbers) {

		boolean transFlag = true;//是否发生交换

		int i=1;

		while (transFlag) {
			transFlag=false;
			for (int j = 0; j < numbers.length - 1; j++) {

				if (numbers[j] < numbers[j + 1]) {

					int temp = numbers[j];
					numbers[j] = numbers[j + 1];
					numbers[j + 1] = temp;
					transFlag=true;
				}
				//LOG.info("{}:{}","第"+i+"趟,第"+(j+1)+"轮",Arrays.toString(numbers));
			}
			//LOG.info("第{}趟:{}",i++,Arrays.toString(numbers));
		}
	}

	/**
	 * 按从小到大排序(从后往前)
	 *
	 * @param numbers 待排序数组
	 */
	public static void sortByAscFromBack(Integer[] numbers){

		boolean transFlag = true;//是否发生交换

		int i=1;

		while (transFlag) {
			transFlag=false;
			for (int j = numbers.length - 1; j>0; j--) {

				if (numbers[j] > numbers[j-1]) {

					int temp = numbers[j];
					numbers[j] = numbers[j - 1];
					numbers[j - 1] = temp;
					transFlag=true;
				}

				//LOG.info("{}:{}","第"+i+"趟,第"+(j+1)+"轮",Arrays.toString(numbers));
			}

			//sLOG.info("第{}趟:{}",i++, Arrays.toString(numbers));
		}
	}

	/**
	 * 按从大到小排序(从后往前)
	 *
	 * @param numbers 待排序数组
	 */
	public static void sortByDescFromBack(Integer[] numbers){

		boolean transFlag = true;//是否发生交换

		int i=1;

		while (transFlag) {
			transFlag=false;
			for (int j = numbers.length - 1; j>0; j--) {

				if (numbers[j] < numbers[j-1]) {

					int temp = numbers[j];
					numbers[j] = numbers[j - 1];
					numbers[j - 1] = temp;
					transFlag=true;
				}

				//LOG.info("{}:{}","第"+i+"趟,第"+(j+1)+"轮",Arrays.toString(numbers));
			}

			//LOG.info("第{}趟:{}",i++, Arrays.toString(numbers));
		}
	}
}
